package jschool.factorization;

import java.util.HashMap;
import java.util.Map;

public class CachedComputable<A, V> implements Computable<A, V> {

	private final Map<A, V> cache = new HashMap<>();
	private final Computable<A, V> computable;
	
	public CachedComputable(Computable<A, V> computable) {
		this.computable = computable;
	}
	
	@Override
	public synchronized V compute(A arg) throws InterruptedException {
		V result = cache.get(arg);
		if (result == null) {
			result = computable.compute(arg);
			cache.put(arg, result);
		}
		return result;
	}

}
